import { useState, useEffect } from 'react';
import { Form, Input, Select, Space, Table, Tag, Button, Modal } from 'antd';
import axios from 'axios';
import { SearchOutlined, UndoOutlined } from '@ant-design/icons';

const LoginLogManagement = () => {
  const [searchForm] = Form.useForm();
  const [data, setData] = useState([]);
  const [filteredData, setFilteredData] = useState([]);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [selectedLog, setSelectedLog] = useState(null);
  const [deleteModalVisible, setDeleteModalVisible] = useState(false);
  const [deleteId, setDeleteId] = useState(null);

  useEffect(() => {
    // 从后端API获取数据
    axios.get('http://localhost:8080/api/loginlog/all')
        .then((response) => {
          setData(response.data);
          setFilteredData(response.data);
        })
        .catch((error) => {
          console.error('Error fetching data:', error);
        });
  }, []);

  const onFinish = (values) => {
    // 根据表单值过滤数据
    const filteredLogs = data.filter((log) => {
      const matchesUsername = !values.username || log.loginName.includes(values.username);
      const matchesIpaddr = !values.ipaddr || log.ipaddr.includes(values.ipaddr);
      const matchesStatus = !values.status || log.status.includes(values.status);

      return matchesUsername && matchesIpaddr && matchesStatus;
    });

    setFilteredData(filteredLogs);
  };

  const resetForm = () => {
    searchForm.resetFields();
    setFilteredData(data);
  };

  const showDetails = (log) => {
    setSelectedLog(log);
    setIsModalVisible(true);
  };

  const handleOk = () => {
    setIsModalVisible(false);
  };

  const showDeleteConfirm = (id) => {
    setDeleteId(id);
    setDeleteModalVisible(true);
  };

  const handleDeleteConfirm = () => {
    axios.delete(`http://localhost:8080/api/loginlog/delete/${deleteId}`)
        .then(() => {
          // 更新数据列表
          setData(data.filter((item) => item.info_id !== deleteId));
          setFilteredData(filteredData.filter((item) => item.info_id !== deleteId));
          setDeleteModalVisible(false);
        })
        .catch((error) => {
          console.error('Error deleting log:', error);
        });
  };

  const handleDeleteCancel = () => {
    setDeleteModalVisible(false);
  };

  const columns = [
    {
      title: '日志编号',
      dataIndex: 'info_id',
      key: 'info_id',
      render: (text) => <a>{text}</a>,
    },
    {
      title: '用户名',
      dataIndex: 'loginName',
      key: 'loginName',
    },
    {
      title: 'IP地址',
      dataIndex: 'ipaddr',
      key: 'ipaddr',
    },
    {
      title: '登录位置',
      dataIndex: 'loginLocation',
      key: 'loginLocation',
    },
    {
      title: '浏览器',
      dataIndex: 'browser',
      key: 'browser',
    },
    {
      title: '操作系统',
      dataIndex: 'os',
      key: 'os',
    },
    {
      title: '登录时间',
      dataIndex: 'loginTime',
      key: 'loginTime',
    },
    {
      title: '状态',
      key: 'status',
      dataIndex: 'status',
      render: (status) => {
        let color = status === 'success' ? 'green' : status === 'failure' ? 'red' : 'geekblue';
        return (
            <Tag color={color}>
              {status.toUpperCase()}
            </Tag>
        );
      },
    },
    {
      title: 'Action',
      key: 'action',
      render: (_, record) => (
          <Space size="middle">
            <a onClick={() => showDetails(record)}>详情</a>
            <a onClick={() => showDeleteConfirm(record.info_id)} style={{ color: '#ed5565' }}>删除</a>
          </Space>
      ),
    },
  ];

  return (
      <div>
        <Form form={searchForm} layout="inline" onFinish={onFinish}>
          <Form.Item name="username" label="用户名">
            <Input placeholder="请输入用户名" />
          </Form.Item>
          <Form.Item name="ipaddr" label="IP地址">
            <Input placeholder="请输入IP地址" />
          </Form.Item>
          <Form.Item name="status" label="状态">
            <Select placeholder="请选择状态">
              <Select.Option value="success">成功</Select.Option>
              <Select.Option value="failure">失败</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item>
            <Space>
              <Button
                  type="primary"
                  htmlType="submit"
                  icon={<SearchOutlined />}
                  style={{ marginLeft: 8, width: 70, backgroundColor: '#1ab394', color: '#fff' }}
              >
                搜索
              </Button>
              <Button
                  onClick={resetForm}
                  icon={<UndoOutlined />}
                  style={{ marginLeft: 8, width: 70, backgroundColor: '#3c79d9', color: '#fff' }}
              >
                重置
              </Button>
            </Space>
          </Form.Item>
        </Form>

        <Table
            columns={columns}
            dataSource={filteredData}
            rowKey="info_id" // 使用 info_id 作为唯一标识符
        />

        <Modal
            title="登录日志详情"
            visible={isModalVisible}
            onOk={handleOk}
            onCancel={handleOk} // 确保点击右上角的关闭按钮也能触发关闭
            footer={null} // 移除底部的所有按钮
        >
          {selectedLog && (
              <div>
                <p><strong>日志编号:</strong> {selectedLog.info_id}</p>
                <p><strong>用户名:</strong> {selectedLog.loginName}</p>
                <p><strong>IP地址:</strong> {selectedLog.ipaddr}</p>
                <p><strong>登录位置:</strong> {selectedLog.loginLocation}</p>
                <p><strong>浏览器:</strong> {selectedLog.browser}</p>
                <p><strong>操作系统:</strong> {selectedLog.os}</p>
                <p><strong>登录时间:</strong> {selectedLog.loginTime}</p>
                <p><strong>状态:</strong> {selectedLog.status}</p>
              </div>
          )}
        </Modal>
        <Modal
            title="确认删除"
            visible={deleteModalVisible}
            onCancel={handleDeleteCancel}
            footer={null} // 移除默认的底部按钮
        >
          <p>你是否确定要删除这条记录?</p>
          <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 16 }}>
            <Button onClick={handleDeleteCancel} style={{ marginLeft: 8, width: 100 }}>取消</Button>
            <Button type="default" onClick={handleDeleteConfirm} style={{ marginLeft: 8, width: 100, backgroundColor: '#ed5565', color: '#fff' }}>确定</Button>
          </div>
        </Modal>
      </div>
  );
};

export default LoginLogManagement;